﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.UserCode;

namespace $rootnamespace$.$subnamespace$
{
    public class $safeitemname$
        : SPFeatureReceiver
    {
        static readonly string AssemblyName = typeof($fileinputname$Proxy).Assembly.FullName;
        static readonly string TypeName = typeof($fileinputname$Proxy).FullName;

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPUserCodeService service = SPUserCodeService.Local;
            if (GetOperation(service) == null)
            {
                SPProxyOperationType operationType = new SPProxyOperationType(AssemblyName, TypeName);
                service.ProxyOperationTypes.Add(operationType);
                service.Update();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPUserCodeService service = SPUserCodeService.Local;
            SPProxyOperationType operationType = GetOperation(service);
            if (operationType != null)
            {
                service.ProxyOperationTypes.Remove(operationType);
                service.Update();
            }
        }

        static SPProxyOperationType GetOperation(SPUserCodeService service)
        {
            return service.ProxyOperationTypes.FirstOrDefault(
                            searchItem => searchItem.AssemblyName == AssemblyName &&
                                searchItem.TypeName == TypeName);
        }
    }
}
